package com.daybook.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.catalina.Session;
import org.eclipse.jdt.internal.compiler.ast.DoubleLiteral;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.daybook.mapper.UserMapper;
import com.daybook.pojo.Category;
import com.daybook.pojo.User;
import com.daybook.service.UserService;
import com.daybook.util.PageHelp;

@Controller
@RequestMapping(value = "/userMsg")
public class UserController {
	@Autowired
	private UserService userService;
	/**
	 * 用户模块
	 * */
	// 注册用户
		@RequestMapping(value = "/registerNewUser", method = RequestMethod.POST)
		public void registerNewUser(HttpServletRequest request, HttpServletResponse response)
				throws IOException, JSONException {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			//获取注册数据
			String uname=request.getParameter("uname");
			String upassword=request.getParameter("upassword");
			String utel=request.getParameter("utel");
			User user=new User();
			user.setUname(uname);
			user.setUpassword(upassword);
			user.setUtel(utel);
			Timestamp createtime=new Timestamp(System.currentTimeMillis());  
			user.setUregtime(createtime);
			user.setUstate(1);
			int result = -1;
			result = userService.registerNewUser(user);
			PrintWriter out = response.getWriter();
			JSONObject obj = new JSONObject();
			obj.put("res", result);
			out.print(obj);
			out.flush();
			out.close();
		}
		// 用户登录
				@RequestMapping(value = "/login", method = RequestMethod.POST)
				public void login(HttpServletRequest request, HttpServletResponse response,HttpSession session, User user)
						throws IOException, JSONException {
					request.setCharacterEncoding("utf-8");
					response.setContentType("text/html;charset=utf-8");
					int result = -1;
					User users = userService.loginUser(user);
					if(users!=null){
						if(users.getUstate()==0){
							result=0;
						}else{
							result=1;
							 session.setAttribute("user",users);	
						}
						
					}else {
						 session.setAttribute("user_error","用户名或者密码错误！");
					}
					PrintWriter out = response.getWriter();
					JSONObject obj = new JSONObject();
					obj.put("res", result);
					out.print(obj);
					
				}
				//注销
			    @RequestMapping(value = "/logout",method = RequestMethod.POST)
			  		private void logout(HttpServletRequest request, HttpServletResponse response) throws  IOException, JSONException {
			  			HttpSession session=request.getSession();
			  			session.getAttribute("user");
			  			PrintWriter out = response.getWriter();
						JSONObject obj = new JSONObject();
			  	        if(session!=null){ 
			  	        	session.removeAttribute("user");  
			  	        	obj.put("res", 1);
			  	        } else{
			  	        	obj.put("res", -1);	
			  	        }
			  	      out.print(obj);
						out.close();	
			  	       
			  		}
				
	//验证用户名是否存在
	@RequestMapping(value = "/getUserByName", method = RequestMethod.POST)
	public void getUserByName(HttpServletRequest request, HttpServletResponse response)
			throws IOException, JSONException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		// 
		String uname = request.getParameter("uname");
		int result=-1;
		result=userService.getUserByname(uname);
	
		PrintWriter out = response.getWriter();
		JSONObject obj = new JSONObject();
		// 用户名存在，不可以注册
		if (result >0) {
			obj.put("valid", false);
			
		} else {
			obj.put("valid", true);
		}
		out.print(obj);
		out.close();
	}
	
	// 验证用户密码是否正确
	@RequestMapping(value = "/getPwd", method = RequestMethod.POST)
	public void getPwd(HttpServletRequest request, HttpServletResponse response,HttpSession session)
			throws IOException, JSONException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String oldpwd=request.getParameter("oldpwd");
		User user =(User)session.getAttribute("user");
		PrintWriter out = response.getWriter();
		JSONObject obj = new JSONObject();
		if (user.getUpassword().equals(oldpwd)) {
			obj.put("valid", true);
			
		} else {
			obj.put("valid", false);
		}
		out.print(obj);
		out.flush();
		out.close();
	}
	// 用户修改密码
		@RequestMapping(value = "/changePwd", method = RequestMethod.POST)
		public void changePwd(HttpServletRequest request, HttpServletResponse response,HttpSession session)
				throws IOException, JSONException {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			String newpwd=request.getParameter("newpwd");
			User user =(User)session.getAttribute("user");
			int result=-1;
			result=userService.updateUserPwd(user.getUid(), newpwd);
			if(result>0){
				session.removeAttribute("user"); 
			}
			PrintWriter out = response.getWriter();
			JSONObject obj = new JSONObject();
			obj.put("res", result);
			out.print(obj);
			out.flush();
			out.close();
		}
		// 用户信息查看
				@RequestMapping(value = "/userInfo", method = RequestMethod.POST)
				public void userInfo(HttpServletRequest request, HttpServletResponse response,HttpSession session)
						throws IOException, JSONException {
					request.setCharacterEncoding("utf-8");
					response.setContentType("text/html;charset=utf-8");
					String newpwd=request.getParameter("newpwd");
					User user =(User)session.getAttribute("user");
					String memberName=userService.getUserMemberGrade(user.getUid());
					List<User> userList = new ArrayList<User>();
					userList.add(user);
					PrintWriter out = response.getWriter();
					JSONObject obj = new JSONObject();
					obj.put("res", 1);
					obj.put("list",userList);
					obj.put("membername", memberName);
					out.print(obj);
					out.flush();
					out.close();
				}
				// 用户信息修改
				@RequestMapping(value = "/changeUserInfo", method = RequestMethod.POST)
				public void changeUserInfo(HttpServletRequest request, HttpServletResponse response,HttpSession session)
						throws IOException, JSONException {
					request.setCharacterEncoding("utf-8");
					response.setContentType("text/html;charset=utf-8");
				
					String relname=request.getParameter("relname");
					String utel=request.getParameter("utel");
					String uaddress=request.getParameter("uaddress");
					String uqq=request.getParameter("uqq");
					String uemail=request.getParameter("uemail");
					User olduser =(User)session.getAttribute("user");
					User newuser=olduser;
					if(olduser!=null){
						newuser.setUid(olduser.getUid());
					}
					if(relname!=null&&!relname.equals("")){
						newuser.setUrelname(relname);
					}
					if(utel!=null&&!utel.equals("")){
						newuser.setUtel(utel);
					}
					if(uaddress!=null&&!uaddress.equals("")){
						newuser.setUaddress(uaddress);
					}
					if(uqq!=null&&!uqq.equals("")){
						newuser.setUqq(uqq);
					}
					if(uemail!=null&&!uemail.equals("")){
						newuser.setUemail(uemail);
					}
					int result=-1;
					result=userService.changeUserByUid(newuser);
					if(result>0){
						session.removeAttribute("user");  
						session.setAttribute("user",newuser);
					}
					PrintWriter out = response.getWriter();
					JSONObject obj = new JSONObject();
					obj.put("res", result);
					out.print(obj);
					out.flush();
					out.close();
				}
	/**************************管理员模块*******************************/
	// 获取用户列表
		@RequestMapping(value = "/getUserList", method = RequestMethod.POST)
		public void getUserList(HttpServletRequest request, HttpServletResponse response)
				throws IOException, JSONException {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			// 获得页码
			String num = request.getParameter("num");
			int pageNow = Integer.valueOf(num);
			User user=new User();
			String uname = request.getParameter("uname");
			if(!uname.equals("")){
				user.setUname(uname);
			}
			String urelname = request.getParameter("urelname");
			if(!urelname.equals("")){
				user.setUrelname(urelname);
			}
			String tel = request.getParameter("utel");
			if(!tel.equals("")){
			user.setUtel(tel);
			}
		
			PageHelp page = userService.getUserList(pageNow, user);
			// 获取总页数
			int totlpage = page.getTotalPageCount();
			// 强制类型转换
			List<User> userList = (List<User>) page.getList();
			PrintWriter out = response.getWriter();
			JSONObject obj = new JSONObject();
			obj.put("res", 1);
			obj.put("totalPage", totlpage);
			obj.put("num", userList.size());
			obj.put("list",userList);
			out.print(obj);
			out.close();
		}
//改变用户状态
		@RequestMapping(value = "/del", method = RequestMethod.POST)
		public void changeUserState(HttpServletRequest request, HttpServletResponse response)
				throws IOException, JSONException {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			// 
			String id = request.getParameter("uid");
			int uid=Integer.valueOf(id);
			String state=request.getParameter("ustate");
			int ustate=Integer.valueOf(state);
			if(ustate==0){
				ustate=1;
			}else {
				ustate=0;
			}
			PrintWriter out = response.getWriter();
			JSONObject obj = new JSONObject();
			int res=userService.changeUserState(uid, ustate);
			obj.put("res", res);
			out.print(obj);
			out.close();
			}
		//获取用户折扣信息
		@RequestMapping(value = "/getUserDiscountInfo", method = RequestMethod.POST)
		public void getUserDiscountInfo(HttpServletRequest request, HttpServletResponse response)
				throws IOException, JSONException {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			HttpSession session=request.getSession();
  			User user=(User)session.getAttribute("user");
  			double discount=1;
  			discount=userService.getUserMember(user.getUid());
			PrintWriter out = response.getWriter();
			JSONObject obj = new JSONObject();
			obj.put("discount", discount);
			out.print(obj);
			out.close();
			}
		
		
}
